package com.ferret.service;

import cn.hutool.core.lang.Console;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ferret.bean.dto.SubscribeObject;
import com.ferret.bean.entity.VIIDServer;
import com.ferret.bean.entity.VIIDSubscribe;
import com.ferret.bean.vo.SubscribesRequest;
import com.ferret.utils.StructCodec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class VIIDSubscribeService {


    @Value("${DeviceID}")
    private String DeviceID;
    @Value("${common.ip}")
    private String commonIp;
    @Value("${server.port}")
    private Integer serverPort;

    public VIIDSubscribe getCacheById(String subscribeId) {
        Optional<VIIDSubscribe> optional = null;
//                viidSubscribeDao.findById(subscribeId);
        return optional.get();
    }

    public String subscribes(VIIDServer domain, String subscribeDetail) {

        String receiveAddr = "http://" + commonIp + ":" + serverPort + "/VIID/SubscribeNotifications";
        String resourceUri = domain.getServerId();
        ObjectMapper mapper = new ObjectMapper();
        SubscribeObject subscribe = StructCodec.inputSubscribeBuilder(resourceUri, "订阅",
                subscribeDetail, domain, receiveAddr);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
        headers.set("User-Identify", DeviceID);
        try {
            String jsonString = mapper.writeValueAsString(SubscribesRequest.create(subscribe));
            HttpResponse execute = HttpRequest.post("http://" + domain.getHost() + ":" + domain.getPort() + "/VIID/Subscribes")
                    .header(headers)
                    .body(jsonString)
                    .execute();
            String body1 = execute.body();
            Console.log(body1);
            VIIDSubscribe entity = StructCodec.castSubscribe(subscribe);
            entity.setBaowen(jsonString);
            entity.setServerId(domain.getServerId());
            return body1;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
